package servlet;

import user.Fruit;
import user.Member;
import user.Register;
import util.DBUtilDao;
import util.MD5;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MD5 md5 = new MD5();
        Member member = null;
        List<Fruit> fruit = null;

        String username = request.getParameter("username");
        String password = md5.getMD5String(request.getParameter("password"));//根据传递过来的密码生成密文
        Register register = new Register(username, password);
        DBUtilDao dbUtilDao = new DBUtilDao();
        try {
            if (dbUtilDao.getOne(register) != null && dbUtilDao.getOne(register).getPassword().equals(password)) {//密码匹配，验证通过
//                response.getWriter().println("验证通过");
                HttpSession session = request.getSession();
                member = dbUtilDao.getMember(register.getPhoneNumber());//根据手机号，查询数据库中的个人中心的信息
                session.setAttribute("username", username);//把当前用户名放进session之后，UpdateShopCarServlet根据用户名查找数据库

                SelectShopCarServlet selectShopCarServlet = new SelectShopCarServlet();
                selectShopCarServlet.doGet(request, response); //从数据库读取购物车

                SelectOrderCarServlet selectOrderCarServlet = new SelectOrderCarServlet();
                selectOrderCarServlet.doGet(request, response);//从数据库读取订单信息（已支付和未支付）

                session.setAttribute("member", member);

                dbUtilDao.close();//释放资源
                request.getRequestDispatcher("member.jsp").forward(request, response);

            } else {
                request.setAttribute("ErrorMessage", "用户名或者密码不正确");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
